package com.hoperun.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.hoperun.bean.AdminManager;
import com.hoperun.bean.AdminManagerRoles;
import com.hoperun.bean.AdminOrganizationsManager;
import com.hoperun.dao.AdminManagerDAO;
import com.hoperun.dao.AdminManagerRolesDAO;
import com.hoperun.dao.AdminOrganizationsManagerDAO;
import com.hoperun.framework.ex.XHZException;
import com.hoperun.framework.ibatis.page.BootGrid;
import com.hoperun.framework.ibatis.page.BootGridPage;
import com.hoperun.framework.query.Criteria;
import com.hoperun.framework.util.Constant;
import com.hoperun.service.IAdminManagerSV;
import com.hoperun.service.IYsSDKSV;
import com.hoperun.utils.ErrorCode;

@Service("adminManagerSV")
public class AdminManagerSVImpl implements IAdminManagerSV {
	@Resource
	private AdminManagerDAO adminManagerDAO;

	@Resource
	private IYsSDKSV ysSDKSV;

	@Resource
	private AdminManagerRolesDAO adminManagerRolesDAO;

	@Resource
	private AdminOrganizationsManagerDAO adminOrganizationsManagerDAO;

	@Override
	public void delete(Long id) throws Exception {
		adminManagerDAO.delete(id);
	}

	@Override
	public AdminManager queryById(Long id) throws Exception {
		return adminManagerDAO.queryById(id);
	}

	@Override
	public AdminManager save(AdminManager adminManager) throws Exception {
		adminManagerDAO.insert(adminManager);
		return adminManager;
	}

	@Override
	public AdminManager register(AdminManager adminManager) throws Exception {

		if (null == adminManager.getAccout()) {
			throw new XHZException(ErrorCode.MEMBER.INFO_EMPTY);
		}

		if (StringUtils.isBlank(adminManager.getAccout())
				|| StringUtils.isBlank(adminManager.getPassword())) {
			throw new XHZException(ErrorCode.MEMBER.ACCOUNT_PASSWORD_ILLEGAL);
		}
		String account = adminManager.getAccout();
		String ys_pwd = adminManager.getSdkPwd();

		Criteria criteria = new Criteria();

		criteria.addEqual(AdminManager.COL_ACCOUT, account, Criteria.AND);
		criteria.limit(Constant.ZERO, Constant.ONE);

		/** 判断该用户名是否已经被注册 */
		if (CollectionUtils.isNotEmpty(adminManagerDAO
				.queryByCondition(criteria))) {
			throw new XHZException(ErrorCode.MEMBER.INFO_EXIST);
		}
		adminManagerDAO.insert(adminManager);

		Integer ret = ysSDKSV.addUser(account, ys_pwd);

		if (null == ret) {
			throw new XHZException(ErrorCode.YS.PRAMS_ERROR);
		}

		/** 添加成功 */
		if (0 == ret) {
			return adminManager;
		}
		/** key认证失败 */
		if (ret == 1007) {
			throw new XHZException(ErrorCode.YS.KEY_FAILD);
		}
		/** 用户名密码格式错误 */
		else if (ret == 1008) {
			throw new XHZException(ErrorCode.YS.ACCOUNT_PASSWORD_ILLEGAL);
		}
		/** 用户名重复 */
		else if (ret == 1002) {
			throw new XHZException(ErrorCode.YS.ACCOUNT_REPEAT);
		}
		/** 参数出错 */
		else if (ret == 9999) {
			throw new XHZException(ErrorCode.YS.PRAMS_ERROR);
		}

		return adminManager;
	}

	@Override
	public void update(AdminManager adminManager) throws Exception {
		adminManagerDAO.update(adminManager);
	}

	@Override
	public void saveOrUpdate(AdminManager adminManager) throws Exception {
		if (adminManager == null)
			return;
		if (StringUtils.isNotBlank("" + adminManager.getManagerId())) {
			update(adminManager);
		} else {
			save(adminManager);
		}
	}

	@Override
	public void saveOrUpdate(List<AdminManager> list) throws Exception {
		if (CollectionUtils.isNotEmpty(list)) {
			for (AdminManager adminManager : list) {
				saveOrUpdate(adminManager);
			}
		}
	}

	@Override
	public List<AdminManager> queryByCondition(Criteria criteria)
			throws Exception {
		return adminManagerDAO.queryByCondition(criteria);
	}

	@Override
	public int queryCountByCondition(Criteria criteria) throws Exception {
		return adminManagerDAO.queryCountByCondition(criteria);
	}

	@Override
	public BootGridPage<AdminManager> queryPage(Criteria criteria,
			BootGrid<AdminManager> grid) throws Exception {

		// AdminManager model = grid.getEntity();

		int totalCount = adminManagerDAO.queryCountByCondition(criteria);

		if (Constant.ZERO < totalCount) {

			Map<String, String> sorts = grid.getSort();

			/** 设置排序规则 **/
			if (MapUtils.isNotEmpty(sorts)) {
				Set<String> keySets = sorts.keySet();
				String sort = "";
				for (String key : keySets) {
					sort += " , " + key + " " + sorts.get(key);
				}
				criteria.orderBy(sort.replaceFirst(",", ""));
			}
			if (grid.getCurrent() >= Constant.ZERO) {
				int start = (grid.getCurrent() - Constant.ONE)
						* grid.getRowCount();
				int size = grid.getRowCount();

				criteria.limit(start, size);
			}
			List<AdminManager> list = adminManagerDAO
					.queryByCondition(criteria);

			if (CollectionUtils.isNotEmpty(list)) {
				for (AdminManager manager : list) {
					criteria = new Criteria(AdminManagerRoles.TABLE_PREFIX);
					criteria.addEqual(AdminManagerRoles.COL_MANAGER_ID,
							manager.getManagerId(), Criteria.AND);
					List<AdminManagerRoles> managerRoles = adminManagerRolesDAO
							.queryBySpecificCondition(criteria);
					if (CollectionUtils.isNotEmpty(managerRoles)) {
						for (AdminManagerRoles managerRole : managerRoles) {
							manager.addRole(managerRole.getAdminRoles());
						}
					}

					criteria = new Criteria(
							AdminOrganizationsManager.TABLE_PREFIX);
					criteria.addEqual(AdminOrganizationsManager.COL_MANAGER_ID,
							manager.getManagerId(), Criteria.AND);
					List<AdminOrganizationsManager> managerOrganizations = adminOrganizationsManagerDAO
							.queryBySpecificCondition(criteria);
					if (CollectionUtils.isNotEmpty(managerOrganizations)) {
						for (AdminOrganizationsManager managerOrganization : managerOrganizations) {
							manager.addOrganization(managerOrganization
									.getAdminOrganizations());
						}
					}

				}
			}

			BootGridPage<AdminManager> page = new BootGridPage<AdminManager>(
					grid.getCurrent(), grid.getRowCount(), totalCount, list);

			return page;
		}
		return new BootGridPage<AdminManager>(grid.getCurrent(),
				grid.getRowCount(), totalCount, new ArrayList<AdminManager>());

	}

}
